package cn.com.template.controller.budgetcalc;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.com.commons.Paginator;
import cn.com.commons.utils.StringUtil;
import cn.com.dal.dataobject.VerifyDO;
import cn.com.dal.dataobject.cs.BranchcostDO;
import cn.com.dal.dataobject.cs.CompanycostDO;
import cn.com.dal.dataobject.hr.UserDO;
import cn.com.service.VerifyService;
import cn.com.service.cs.BranchcostService;
import cn.com.service.cs.CompanycostService;
import cn.com.service.hr.UserService;
import cn.com.support.context.UserContext;
import cn.com.support.message.MessageResult;
import cn.com.support.utils.JacksonUtil;
import cn.com.support.utils.VerifyConfigInf;
import cn.com.template.ui.Flexigrid;
import cn.com.template.utils.FlexigridUtil;

/**
 * 
 * 预核算审核控制器
 * 
 * @since 1.0 2012-2-21 下午11:03:53
 * @version $Id$
 * @author Zoe
 */
@Controller
@RequestMapping("/budgetcalc/verify")
public class VerifyController {

	@Autowired
	private VerifyService verifyService;
	
	@Autowired
	private BranchcostService branchcostService;
	
	@Autowired
	private CompanycostService companycostService;
	
	@Autowired
	private UserService userService;
	
	@RequestMapping
	public ModelAndView forwardVerify() {
		ModelAndView mav = new ModelAndView("budgetcalc/verify");
		return mav;
	}
	
	@RequestMapping("getCostDetail/{bizId}/{module}/{id}")
	public ModelAndView getCostDetail(@PathVariable("bizId") Long bizId, @PathVariable("module") String module,@PathVariable("id") Long id, HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("budgetcalc/costdetail");
		BranchcostDO branchcostDO = null;
		CompanycostDO companycostDO = null;
		//System.out.println(id+"----"+module);
		if(!StringUtil.isNotBlank(module)){
			return new ModelAndView("404");
		}
		//request.setAttribute("module", module);
		VerifyDO verifyDO = verifyService.selectById(id).getData();
		request.setAttribute("verify", verifyDO);
		//返回指定审核人信息
		List<Map<String, Object>> roleLst = JacksonUtil.jsonArr2Lst(verifyDO.getAttribute());
		Map<Object, Object> params = null;
		List<UserDO> verifyLst = new ArrayList<UserDO>();
		if(verifyDO.getLevel() < roleLst.size()){
			for(Map<String, Object> roleMap : roleLst){
				if(roleMap.get("level").equals(verifyDO.getLevel()+1)){
					params = new HashMap<Object, Object>();
					//有效的用户
					params.put("status", 1);
					params.put("roleId", roleMap.get("id"));
					verifyLst = userService.selectListByRole(params);
					break;
				}
			}
		}
		request.setAttribute("verifyLst", verifyLst);
		//返回报销详细数据
		if(module.equals(VerifyConfigInf.BRANCH_COST_VERIFY)){
			branchcostDO =  branchcostService.selectTotalById(bizId);
			request.setAttribute("costDetail", branchcostDO);
		}else if(module.equals(VerifyConfigInf.COMPANY_COST_VERIFY)){
			companycostDO =  companycostService.selectTotalById(bizId);
			request.setAttribute("costDetail", companycostDO);
		}else{
			return mav;
		}
		return mav;
	}
	
	@RequestMapping("/getVerify")
	@ResponseBody
	public Flexigrid getVerify(HttpServletRequest request){
		Flexigrid flexigrid = null;
		BranchcostDO branchcostDO = null;
		CompanycostDO companycostDO = null;
		try {
			Paginator<VerifyDO, List<VerifyDO>> paginator = new Paginator<VerifyDO, List<VerifyDO>>();
			VerifyDO verifyDO = new VerifyDO();
			verifyDO.setVerifier(UserContext.getUsername());
			String status = request.getParameter("status");
			String dateFrom =  request.getParameter("dateFrom");
			String dateTo =  request.getParameter("dateTo");
			if(StringUtil.isNotBlank(status)){
				verifyDO.setStatus(Byte.valueOf(status.trim()));
			}
			if(StringUtil.isNotBlank(dateFrom)){
				verifyDO.setDateFrom(dateFrom.trim());
			}
			if(StringUtil.isNotBlank(dateTo)){
				verifyDO.setDateTo(dateTo.trim());
			}
			paginator.setCondition(verifyDO);
			// 设置分页器
			paginator.setPageSize(Integer.parseInt(request.getParameter("rp")));
			paginator.setCurrentPage(Integer.parseInt(request.getParameter("page")));
			paginator = verifyService.selectByPage(paginator);
			//获取审核数据
			List<VerifyDO> res = paginator.getResult();
			String module = "";
			for(VerifyDO obj : res){
				module = obj.getModule();
				if(module.equals(VerifyConfigInf.BRANCH_COST_VERIFY)){
					branchcostDO = branchcostService.selectTotalById(obj.getBizId());
					obj.setProjectName(branchcostDO.getProjectName());
					obj.setRefundUser(branchcostDO.getRefundUser());
					obj.setGmtRefund(branchcostDO.getGmtRefund());
					obj.setTotalCost(branchcostDO.getTotalCost());
				}
				if(module.equals(VerifyConfigInf.COMPANY_COST_VERIFY)){
					companycostDO = companycostService.selectTotalById(obj.getBizId());
					obj.setProjectName(companycostDO.getProjectName());
					obj.setRefundUser(companycostDO.getRefundUser());
					obj.setGmtRefund(companycostDO.getGmtRefund());
					obj.setTotalCost(companycostDO.getTotalCost());
				}
			}
			//PACKAGE FLEXIGRID DATA
			flexigrid = FlexigridUtil.formatFlexigridData(paginator);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flexigrid;
	}

	
	/**
		* @Title: verifyCost 
		* @param id
		* @param statusStr
		* @param verifier
		* @param reason
		* @return MessageResult<Integer>
		* @Author Zoe 
		* @Version 1.0.0 2012-4-11
	 */
	@RequestMapping(value="/verifyCost", method=RequestMethod.POST)
	@ResponseBody
	public MessageResult<Integer> verifyCost(@RequestParam Long id, String statusStr, String verifier, String reason){
		MessageResult<Integer> result = new MessageResult<Integer>(false, 0);
		Map<Object, Object> params = null;
		VerifyDO verifyDO = null;
		BranchcostDO branchcostDO = null;
		CompanycostDO companycostDO = null;
		//List<VerifyDO> verifyLst = null;
		Byte status = null;
		verifier =(verifier == null?"ADMIN":verifier);
		try {
			String username = UserContext.getUsername();
			params = new HashMap<Object, Object>();
			if(null != id){
				verifyDO = verifyService.selectById(id).getData();
				if(null == verifyDO){
					return result;
				}
				params.put("bizId", verifyDO.getBizId());
				params.put("module", verifyDO.getModule());
				//verifyLst = verifyService.selectList(params);
				List<Map<String, Object>> roleLst = JacksonUtil.jsonArr2Lst(verifyDO.getAttribute());
				//System.out.println(statusStr);
				//System.out.println(statusStr.equals("pass"));
				//用户审核结果STR
				if(statusStr.equals("pass")){
					status = VerifyDO.STATUS_PASS;
				}else{
					status = VerifyDO.STATUS_REJECT;
				}
				//System.out.println(status);
				//当审核表中该数据审核记录数 == 审核配置的审核级别LEVEL
				//if(verifyLst.size() == roleLst.size()){
				if(verifyDO.getLevel() == roleLst.size() || status == VerifyDO.STATUS_REJECT){	
					//更新报销数据表STATUS
					//branchCost and companyCost
					if(verifyDO.getModule().equals(VerifyConfigInf.BRANCH_COST_VERIFY)){
						branchcostDO = new BranchcostDO();
						branchcostDO.setId(verifyDO.getBizId());
						branchcostDO.setStatus(status);
						//将审核结果描述存入Description字段
						branchcostDO.setDescription(reason);
						branchcostService.updateById(branchcostDO);
					}else if(verifyDO.getModule().equals(VerifyConfigInf.COMPANY_COST_VERIFY)){
						companycostDO = new CompanycostDO();
						companycostDO.setId(verifyDO.getBizId());
						companycostDO.setStatus(status);
						//将审核结果描述存入Description字段
						companycostDO.setDescription(reason);
						companycostService.updateById(companycostDO);
					}else{
						System.err.println("Out of verify config!");
					}
				//}else if(verifyLst.size() < roleLst.size()){
				}else if(verifyDO.getLevel() < roleLst.size() && status == VerifyDO.STATUS_PASS){
					//当审核结果PASS时
					//当改数据审核记录数 < 审核级别LEVEL时
					//加入新的审核记录~交给下级审核角色审核
					//审核记录LEVEL:+1入库
					VerifyDO newLvLDO = new VerifyDO();
					newLvLDO.setBizId(verifyDO.getBizId());
					newLvLDO.setVerifier(verifier);
					newLvLDO.setModule(verifyDO.getModule());
					newLvLDO.setLevel((byte)(verifyDO.getLevel()+1));
					newLvLDO.setStatus((byte)VerifyDO.STATUS_DOING);
					newLvLDO.setSort((byte)VerifyDO.STATUS_DOING);
					newLvLDO.setAttribute(verifyDO.getAttribute());
					newLvLDO.setCreator(username);
					//审核发起人为第一次创建人
					//所有级别的审核发起人都为同一人
					newLvLDO.setSubmitter(verifyDO.getSubmitter());
					verifyService.insert(newLvLDO);
				}else{
					//level out of range
					System.err.println("Out of verify config!");
				}
				
				//设置状态PASS
				verifyDO.setDescription(reason);
				verifyDO.setStatus(status);
				result = verifyService.updateById(verifyDO);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
